package com.dd.cloud.common.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.dd.cloud.common.annotate.FileSuffix;
import com.dd.cloud.common.config.common.SpringContextJobUtil;
import com.dd.cloud.common.config.obs.PathProperties;
import com.dd.cloud.common.utils.FileUrlPrefixUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @Description: // jackson的自定义反序列化
 * @ClassName: JscksonDeserializer    // 类名，会自动填充
 * @Author: czg          // 创建者
 * @Date: 2022/9/22 9:54   // 时间
 * @Version: 1.0     // 版本
 */
@Slf4j
public class FileSuffixDeserializer extends JsonDeserializer {

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        log.info(jsonParser.toString());
        // 获取当前反序列化的对象类型
        Class<?> clazz = jsonParser.getCurrentValue().getClass();
        Field declaredField = null;
        try {
            // 通过字段名称获取对应字段
            // 需考虑继承情况
            declaredField = clazz.getDeclaredField(jsonParser.getCurrentName());
        } catch (NoSuchFieldException e) {
            return jsonParser;
        }
        // 获取注解
        FileSuffix annotation = declaredField.getAnnotation(FileSuffix.class);
        if (annotation == null) {
            return jsonParser;
        }
        String url = jsonParser.getValueAsString();
        boolean scale = annotation.head();
        PathProperties path = (PathProperties) SpringContextJobUtil.getBean("pathProperties");
        FileUrlPrefixUtils prefixUtils = new FileUrlPrefixUtils(path.getImageServer(), path.getAgentServer());
        if (!scale) {
            return prefixUtils.deleteImageServer(url);
        } else {
            return prefixUtils.addImageServer(url);
        }
    }
}
